/*
 * Copyright (c) 2021 HPMicro
 *
 * SPDX-License-Identifier: BSD-3-Clause
 *
 */

#include "board.h"
#include "hpm_sdmmc_sd.h"
#include "ff.h"
#include "diskio.h"
#include "hpm_gptmr_drv.h"
#include "hpm_gpio_drv.h"

extern sd_card_t g_sd;

static FATFS fdisk;

bool status_changed = false;
bool inserted = false;
bool removed = false ;


FATFS s_sd_disk;
FIL s_file;
DIR s_dir;
FRESULT fatfs_result;
BYTE work[FF_MAX_SS];

const TCHAR driver_SD_num_buf[3] = {DEV_SD + '0', ':', '/'};

FRESULT sd_fatfs_mount(void)
{
    FILINFO fileinfo;
    DIR dir;
    FRESULT fatfs_result;
    fatfs_result = f_mount(&fdisk, driver_SD_num_buf, 1);
    if (fatfs_result == FR_OK) {
        printf("SD card has been mounted successfully\n");
    } else {
        printf("Failed mounted.[%d]\n", fatfs_result);
    }
    f_chdrive(driver_SD_num_buf);
    return fatfs_result;
}

void sd_fatfs_remount()
{
    FRESULT fatfs_result;
    fatfs_result = f_unmount(driver_SD_num_buf);
    if(fatfs_result == FR_OK){
        printf("TF unmouted.\n");
        printf("Remove phy disk\n");
        
    }
    else{
        printf("TF unmounted fail\r\n");
    } 
}

#define TEST_DIR_NAME "hpmicro_sd_test_dir0"

void isr_SDXC(void)
{ 
    uint32_t status;
    status_changed = true;
    status = sdxc_get_interrupt_status(HPM_SDXC1); 
    sdxc_clear_interrupt_status(HPM_SDXC1,status);
    if(status & SDXC_INT_SIGNAL_EN_CARD_INSERTION_SIGNAL_EN_MASK)
    {
        printf("insert\r\n");
        inserted = true;

    }else if(status & SDXC_INT_SIGNAL_EN_CARD_REMOVAL_SIGNAL_EN_MASK){
        memset(&g_sd, 0, sizeof(g_sd));
        if (sd_init(&g_sd) != status_success) {
            memset(&g_sd, 0, sizeof(g_sd));
        }
        printf("remove\r\n");
        removed = true;
    }
}
SDK_DECLARE_EXT_ISR_M(IRQn_SDXC1, isr_SDXC)

void fatfs_task(void)
{
    
        if(inserted == true)
        {
            sd_fatfs_mount();
            inserted = false;
        }
        else if(removed == true)
        {
            sd_fatfs_remount();
            removed = false;
        }
    
    status_changed = false;
}


